<template>
  <VZPanel title="故障件生产批次分布" simple iconText="mdi-chart-pie">
    <div style="margin:-16px">
      <v-card>
        <v-row>
          <v-col cols="3">
            <v-autocomplete
                    v-model="selectedReferred"
                    :items="referredItems"
                    item-text="text"
                    item-value="id"
                    label="搜索零件简称"
                    outlined
                    dense
                    clearable
                    :filter="customFilter"
                    :loading="loading"
                    multiple
            ></v-autocomplete>
          </v-col>
          <v-col cols="3">
            <v-autocomplete
                    v-model="selectedMaterial"
                    :items="materialItems"
                    item-text="text"
                    item-value="id"
                    label="搜索产品"
                    outlined
                    dense
                    clearable
                    :filter="customFilter"
                    :loading="loading"
            ></v-autocomplete>
          </v-col>
          <v-col cols="2">
            <v-menu
                    ref="startMenu"
                    v-model="startMenu"
                    :close-on-content-click="false"
                    max-width="290"
                    min-width="290"
                    offset-y
            >
              <template v-slot:activator="{ on, attrs }">
                <v-text-field
                        v-model="startYear"
                        label="起始日期"
                        readonly
                        v-bind="attrs"
                        v-on="on"
                        outlined
                        dense
                ></v-text-field>
              </template>
              <v-date-picker
                      v-model="startYear"
                      type="month"
                      @change="startMenu = false"
                      :max="endYear"
                      locale="zh-cn"
                      :allowed-dates="allowedDates"
              ></v-date-picker>
            </v-menu>
          </v-col>
          <v-col cols="2">
            <v-menu
                    ref="endMenu"
                    v-model="endMenu"
                    :close-on-content-click="false"
                    max-width="290"
                    min-width="290"
                    offset-y
            >
              <template v-slot:activator="{ on, attrs }">
                <v-text-field
                        v-model="endYear"
                        label="结束日期"
                        readonly
                        v-bind="attrs"
                        v-on="on"
                        outlined
                        dense
                ></v-text-field>
              </template>
              <v-date-picker
                      v-model="endYear"
                      type="month"
                      @change="endMenu = false"
                      :min="startYear"
                      locale="zh-cn"
                      :allowed-dates="allowedDates"
              ></v-date-picker>
            </v-menu>
          </v-col>
          <v-spacer></v-spacer>
          <v-col cols="auto" class="d-flex align-center">
            <v-tooltip bottom>
              <template v-slot:activator="{ on, attrs }">
                <v-btn
                  icon
                  color="success"
                  @click="exportToCSV"
                  :disabled="loading"
                  class="mr-2"
                  v-bind="attrs"
                  v-on="on"
                  style="width: 36px; height: 36px"
                >
                  <v-icon size="24">mdi-file-excel</v-icon>
                </v-btn>
              </template>
              <span>导出Excel</span>
            </v-tooltip>
            <v-tooltip bottom>
              <template v-slot:activator="{ on, attrs }">
                <v-btn
                  icon
                  color="primary"
                  @click="exportChart"
                  :disabled="loading"
                  v-bind="attrs"
                  v-on="on"
                  style="width: 36px; height: 36px"
                >
                  <v-icon size="24">mdi-image</v-icon>
                </v-btn>
              </template>
              <span>导出图片</span>
            </v-tooltip>
          </v-col>
        </v-row>
        <div ref="target" style="width:100%;height:400px"></div>
        <v-row class="mt-2">
          <v-col cols="12">
            <v-card class="pa-2">
              <div class="text-subtitle-1 mb-2">生产日期分布</div>
              <v-row dense>
                <v-col v-for="(item, index) in tableItems" :key="index" cols="3" sm="2" md="2">
                  <v-card outlined class="text-center pa-1">
                    <div class="text-caption">{{ item.name }}</div>
                    <div class="text-subtitle-2 primary--text">{{ item.num }}</div>
                  </v-card>
                </v-col>
              </v-row>
            </v-card>
          </v-col>
        </v-row>
      </v-card>
    </div>
  </VZPanel>
</template>

<script>
  export default {
    data() {
      return {
        nameList: [],
        numList: [],
        sql: "SELECT DATE_FORMAT(back_month, '%m') AS `name`,COUNT(*) AS num " +
                "FROM tt_sale_record_qms a " +
                "WHERE a.MATERIAL_ID = 135068 AND DATE_FORMAT(back_month, '%Y') = '2024'     " +
                "GROUP BY DATE_FORMAT(back_month, '%m') ORDER BY `name`; ",
        materialSql: "SELECT id,CONCAT(name,'   ',ASSEMBLY_CODE) name FROM tb_standard_assembly_product WHERE MARK_FOR_DELETE = 0",
        referredSql: "SELECT c.id,CONCAT(c.SIMPLE_CALL,'   ',c.CODE) name FROM tt_sale_record_qms a  " +
                "LEFT JOIN tb_standard_assembly_product b ON a.MATERIAL_ID = b.ID " +
                "LEFT JOIN tb_standard_assembly_product_referred c ON c.id = b.REFERRED_ID " +
                "WHERE c.SIMPLE_CALL IS NOT NULL  " +
                "GROUP BY c.ID ",
        materialItems: [],
        referredItems: [],
        searchMaterial: '',
        selectedMaterial: '',
        selectedReferred: [],
        yearOptions: [],
        startYear: '',
        endYear: '',
        startMenu: false,
        endMenu: false,
        loading: true,
        yearData: {},
        materialIds: [],
        tableHeaders: [],
        tableItems: [],
      }
    },
    computed: {
      years() {
        if (!this.startYear || !this.endYear) return [];
        const start = parseInt(this.startYear);
        const end = parseInt(this.endYear);
        return Array.from({length: end - start + 1}, (_, i) => String(start + i));
      }
    },
    methods: {
      allowedDates(val) {
        return true; // 允许选择所有日期
      },
      run() {
        if (!this.chartTarget) {
          this.chartTarget = this.$echarts.init(this.$refs.target);
        }
        let _this = this;
        this.chartTarget.clear();
        let option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: (params) => {
              return `${params[0].name}<br/>数量: ${params[0].value}个`;
            }
          },
          toolbox: {
            feature: {}
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: this.nameList,
            axisLabel: {
              interval: 0,
              rotate: 45
            }
          },
          yAxis: {
            type: 'value',
            name: '数量',
            axisLabel: {
              formatter: '{value} 个'
            }
          },
          series: [{
            data: this.numList,
            type: 'bar',
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  position: 'top',
                  textStyle: {
                    color: '#88aecc',
                    fontSize: 12
                  }
                }
              }
            }
          }]
        }
        this.chartTarget.setOption(option);
        this.chartTarget.on('click', function (params) {
          let dateRange = params.name;
          let startDate, endDate, made_time_null;
          
          if (dateRange === '无日期') {
              made_time_null = 1;
          } else {
            const [year, month] = dateRange.split('-');
            startDate = `${year}-${month}-01`;
            const lastDay = new Date(parseInt(year), parseInt(month), 0).getDate();
            endDate = `${year}-${month}-${lastDay}`;
          }
          
          _this.$emit('toPage', 'v4a964e28354dd5945af2da28ad', {
            material_id: _this.materialIds.join(','),
            btime: startDate,
            etime: endDate,
            made_time_null: made_time_null
          });
        });
        this.updateTableData();
        
      },
      search_data() {
        if (this.materialIds.length === 0) {
          return;
        }
        let _this = this;
        this.loading = true;
        let params = {
          "SQL": `SELECT
                    CASE
                      WHEN MADE_TIME IS NULL THEN '无日期'
                      ELSE DATE_FORMAT(MADE_TIME, '%Y-%m')
                    END AS name,
                    COUNT(*) AS num
                    FROM tt_sale_record_qms a
                    WHERE a.MARK_FOR_DELETE = 0 AND a.MATERIAL_ID in (${this.materialIds.join(',')})
                    AND (MADE_TIME IS NULL
                      OR (DATE_FORMAT(MADE_TIME, '%Y-%m') >= '${this.startYear}'
                      AND DATE_FORMAT(MADE_TIME, '%Y-%m') <= '${this.endYear}'))
                    GROUP BY
                      CASE
                        WHEN MADE_TIME IS NULL THEN '无日期'
                        ELSE DATE_FORMAT(MADE_TIME, '%Y-%m')
                      END
                    ORDER BY
                      CASE
                        WHEN name = '无日期' THEN 1
                        ELSE 0
                      END,
                      name;`
        };
        app.utils.ajaxRequest({
          hideMsg: true,
          hideMask: true,
          url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
          params: {
            functionParam: JSON.stringify(params)
          },
          callBack(res) {
            if (res.success) {
              _this.nameList = res.rows.map(item => item.name);
              _this.numList = res.rows.map(item => item.num);
              _this.run();
            }
            _this.loading = false;
          },
        });
      },
      loadReferredData() {
        let _this = this;
        _this.referredItems = [];
        let params = {"SQL": this.referredSql};
        app.utils.ajaxRequest({
          hideMsg: true,
          hideMask: true,
          url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
          params: {
            functionParam: JSON.stringify(params)
          },
          callBack(res) {
            if (res.success && res.rows.length > 0) {
              let dataList = res.rows;
              let referredList = [];
              dataList.forEach((item) => {
                let map = {};
                map.text = item.name;
                map.id = item.id;
                referredList.push(map);
              })
              _this.referredItems = referredList;
              if (_this.referredItems.length > 0) {
                _this.selectedReferred = [_this.referredItems[0].id];
                _this.loadMaterialIdsByReferred().then(() => {
                  if (_this.materialIds.length > 0) {
                    _this.search_data();
                  }
                });
              }
            }
          },
        })
      },
      loadMaterialData() {
        let _this = this;
        _this.materialItems = [];
        let params = {"SQL": this.materialSql};
        app.utils.ajaxRequest({
          hideMsg: true,
          hideMask: true,
          url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
          params: {
            functionParam: JSON.stringify(params)
          },
          callBack(res) {
            if (res.success && res.rows.length > 0) {
              let dataList = res.rows;
              let materialList = [];
              dataList.forEach((item) => {
                let map = {};
                map.text = item.name;
                map.id = item.id;
                materialList.push(map);
              })
              _this.materialItems = materialList;
            }
            _this.loading = false;
          },
        })
      },
      loadMaterialIdsByReferred() {
        if (!this.selectedReferred.length) {
          this.materialIds = this.selectedMaterial ? [this.selectedMaterial] : [];
          return Promise.resolve();
        }
        let _this = this;
        let params = {
          "SQL": `SELECT DISTINCT a.id
                  FROM tb_standard_assembly_product a
                  WHERE a.MARK_FOR_DELETE = 0
                  AND a.REFERRED_ID IN (${this.selectedReferred.join(',')})`
        };
        return new Promise((resolve) => {
          app.utils.ajaxRequest({
            hideMsg: true,
            hideMask: true,
            url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
            params: {
              functionParam: JSON.stringify(params)
            },
            callBack(res) {
              if (res.success && res.rows.length > 0) {
                _this.materialIds = res.rows.map(item => item.id);
              } else {
                _this.materialIds = [];
              }
              resolve();
            },
          });
        });
      },
      initYearOptions() {
        const currentDate = new Date();
        const currentYear = currentDate.getFullYear();
        const currentMonth = String(currentDate.getMonth() + 1).padStart(2, '0');
        this.endYear = `${currentYear}-${currentMonth}`;
        const startDate = new Date(currentDate);
        startDate.setFullYear(currentYear - 3);
        this.startYear = `${startDate.getFullYear()}-${String(startDate.getMonth() + 1).padStart(2, '0')}`;
      },
      reset() {
        this.searchMaterial = '';
        this.selectedMaterial = '';
        this.selectedReferred = [];
        this.startYear = '';
        this.endYear = '';
        this.search_data();
      },
      customFilter(item, queryText, itemText) {
        const textOne = itemText.toLowerCase();
        const searchText = queryText.toLowerCase();
        return textOne.indexOf(searchText) > -1;
      },
      updateTableData() {
        this.tableItems = this.nameList.map((name, index) => ({
          name: name === '无日期' ? '无日期' : name,
          num: this.numList[index]
        }));
      },
      exportToCSV() {
        try {
          // 准备CSV数据
          let csvContent = "\ufeff"; // 添加BOM头
          csvContent += "故障件生产批次分布\n\n";
          
          // 添加表头
          csvContent += "生产日期,数量\n";
          
          // 添加数据行
          this.tableItems.forEach(item => {
            // 格式化日期
            let formattedDate = item.name;
            if (item.name !== '无日期') {
              const [year, month] = item.name.split('-');
              formattedDate = `${year}年${parseInt(month)}月`;
            }
            csvContent += `${formattedDate},${item.num}\n`;
          });
          
          // 创建Blob对象，指定编码为UTF-8
          const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
          
          // 创建下载链接
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.download = '故障件生产批次分布.csv';
          
          // 触发下载
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          
        } catch (error) {
          console.error('导出CSV失败:', error);
          app.utils.showMessage('导出CSV失败，请稍后重试');
        }
      },
      exportChart() {
        try {
          if (!this.chartTarget) {
            app.utils.showMessage('图表未初始化，请稍后重试');
            return;
          }
          
          // 获取图表的base64图片数据
          const imageUrl = this.chartTarget.getDataURL({
            type: 'png',
            pixelRatio: 2, // 提高图片质量
            backgroundColor: '#fff'
          });
          
          // 创建下载链接
          const link = document.createElement('a');
          link.download = '故障件生产批次分布图表.png';
          link.href = imageUrl;
          
          // 触发下载
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          
        } catch (error) {
          console.error('导出图表失败:', error);
          app.utils.showMessage('导出图表失败，请稍后重试');
        }
      },
    },
    watch: {
      selectedMaterial() {
        if (this.selectedMaterial) {
          this.selectedReferred = [];
          this.materialIds = [this.selectedMaterial];
          this.search_data();
        }
      },
      async selectedReferred() {
        if (this.selectedReferred.length) {
          this.selectedMaterial = '';
          await this.loadMaterialIdsByReferred();
          if (this.materialIds.length > 0) {
            this.search_data();
          }
        } else {
          if (!this.selectedMaterial) {
            this.materialIds = [];
          }
        }
      },
      startYear() {
        if (this.materialIds.length > 0) {
          this.search_data();
        }
      },
      endYear() {
        if (this.materialIds.length > 0) {
          this.search_data();
        }
      }
    },
    created() {
      this.initYearOptions();
      this.loadMaterialData();
      this.loadReferredData();
      setTimeout(() => {
        this.search_data();
      }, 1000);
    },
    mounted() {
      window.onresize = () => {
        this.chartTarget.resize();
      }
    },
  }
</script>
